/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: YinJianFeng
 * @Date: 2024-03-22 11:02:19
 */
import { ArrayUtils, CMEVENTS, DocumentObject } from '@amcax/base';
import { wsApi } from '../server/wsApi';
import { dataManager, userEvents } from '../module';

export class DocumentManager {
  private static instance: DocumentManager;
  private _documentObjects: DocumentObject[] = [];
  private _flatDocumentObjects: DocumentObject[] = [];
  private _isEmptyDocument: boolean = true;

  private constructor() {}

  static getInstance(): DocumentManager {
    if (!DocumentManager.instance) {
      DocumentManager.instance = new DocumentManager();
    }
    return DocumentManager.instance;
  }

  get documentObjects() {
    return this._documentObjects;
  }
  set documentObjects(objects: DocumentObject[]) {
    this._documentObjects = objects;
    if (!objects) return;
    this._flatDocumentObjects = ArrayUtils.flatArray(objects, []);
  }

  get flatDocumentObjects() {
    return this._flatDocumentObjects;
  }

  get isEmptyDocument() {
    return this._isEmptyDocument;
  }
  set isEmptyDocument(b: boolean) {
    this._isEmptyDocument = b;
  }

  async updateDocumentObjects(dxids?: string[]) {
    return new Promise(async (res) => {
      const { objects } = await wsApi.getObjects(); // 暂时拉取所有documentObjects，后面再进行优化
      console.log('updateDocumentObjects', objects);
      // ctx2.setDocumentObjects(objects)
      this.documentObjects = objects;
      userEvents.emit(CMEVENTS.DOCUMENTS_CHANGE, objects);
      if (!objects || objects.length === 0) {
        this.isEmptyDocument = true;
        res(true);
      } else {
        // 储存objects信息，如果有dxids则先过滤一遍
        // 拉平documentObjects,且过滤掉shape为空的object
        const _objects = this.flatDocumentObjects.filter(
          (object: any) => object.shape !== '' && object.shape != null,
        );
        // 过滤会导致洞口无法添加
        // if (dxids && dxids.length > 0) {
        //   _objects = objects.filter((object: any) => dxids.includes(object.dxid))
        // }
        console.log('_objects', _objects, dxids);
        _objects.forEach((object: any) => {
          dataManager.addObjectsInfo(object);
        });
        res(true);
      }
    });
  }

  updateDocumentMaterials() {
    return new Promise(async (res) => {
      const materials = await wsApi.getDocumentMaterials();
      dataManager.setMaterials(materials);
      res(true);
    });
  }

  getProperty() {
    return new Promise(async (res) => {
      const materials = await wsApi.getDocumentMaterials();
      dataManager.setMaterials(materials);
      res(true);
    });
  }
}

export const docMgr = DocumentManager.getInstance();
